<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react-to-wc</title>
    <script src="../libs/react.production.min.js"></script>
    <script src="../libs/react-dom.production.min.js"></script>
  </head>
  <body>
    <div>
      <button id="add">添加HelloWorld</button>
      <button id="modify">更改第一个helloworld的msg</button>
      <button id="remove">删除第一个HelloWorld</button>
    </div>
    <hello-world msg="React">
      <div style="color: chocolate; font-weight: bold">外部HTML内容</div>
    </hello-world>
    <hello-web-component></hello-web-component>
    <script>
      // DOMContentLoaded 事件在 DOM 加载完成后就会触发，不需要等待样式表、图像等资源加载完成，执行速度更快
      // document.addEventListener('DOMContentLoaded', () => {})
      window.addEventListener("load", () => {
        // 所有脚本内容放在这里
        const eventHandler = (e) => {
          alert(e.detail.msg);
        };

        // 注册全部组件
        ReactWebComponents.registerWebComponents();

        const helloWorld = document.querySelector("hello-world");
        // 监听hello-world组件的广播的事件
        helloWorld.addEventListener("myEvent", eventHandler);

        // 添加
        const addButton = document.querySelector("#add");
        addButton.addEventListener("click", () => {
          const element = document.createElement("hello-world");
          const helloWorldNum = document.querySelectorAll("hello-world").length;
          element.setAttribute("msg", `React${helloWorldNum + 1}`);
          document.body.appendChild(element);

          element.addEventListener("myEvent", eventHandler);
        });

        // 修改
        const modifyButton = document.querySelector("#modify");
        modifyButton.addEventListener("click", () => {
          const element = document.querySelector("hello-world");
          element.setAttribute("msg", "World");
        });

        // 删除
        const removeButton = document.querySelector("#remove");
        removeButton.addEventListener("click", () => {
          const element = document.querySelector("hello-world");
          element.remove();
          // 移除监听
          element.removeEventListener("myEvent", eventHandler);
        });
      });
    </script>
  </body>
</html>
